package com.inspectortime.webapp.inspector.reports;

import java.util.Collection;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;

import com.inspectortime.domain.Inspection;
import com.inspectortime.domain.Inspector;
import com.inspectortime.domain.InspectorCompany;
import com.inspectortime.webapp.util.HttpSessionUtils;

public class ActivityReportController extends ReportsController {
	
private static Log log = LogFactory.getLog(ActivityReportController.class);
	
/*	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		return new ActivityReportForm();
	}
*/	
	
	protected ModelAndView onSubmit(HttpServletRequest request,	HttpServletResponse response, Object command, BindException errors)
		throws Exception {
		
		ActivityReportForm form = (ActivityReportForm) command;
		
		InspectorCompany company = HttpSessionUtils.retrieveLoggedInCompany(request, this.getRepository());
		
		List<Inspection> inspections = null;
		Inspector inspector = null;
		
		if (StringUtils.hasText(form.getInspectorId())) {
			Collection<Inspector> inspectors = company.getInspectors();
			for (Inspector tempInspector : inspectors) {
				if (tempInspector.getId().equals(form.getInspectorId())) {
					inspector = tempInspector;
					break;
				}
			}
			inspections = inspector.findInspectionsBetween(form.getStartDate().getTime(), form.getEndDate().getTime());
		
		} else {
			inspections = company.findInspectionsBetween(form.getStartDate().getTime(), form.getEndDate().getTime());
		}
		
		ModelAndView mv = new ModelAndView(getSuccessView(), errors.getModel());
		mv.addObject("selectedInspector", inspector);
		mv.addObject("inspectorCompany", company);
		mv.addObject("inspections", inspections);
		return mv;
		
	}


}
